package com.qf.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public abstract class AbsAdapter<T> extends BaseAdapter {

	private Context context;
	private List<T> datas;
	private int layoutRes; //item布局资源标识
	
	public AbsAdapter(Context context, int layoutRes, List<T> datas) {
		this.context = context;
		this.datas = datas;
		this.layoutRes=layoutRes;
	}

	@Override
	public int getCount() {
		return datas.size();
	}

	@Override
	public Object getItem(int position) {
		return datas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder vHolder=null;
		if(convertView==null){
			convertView=LayoutInflater.from(context).inflate(layoutRes, null);
			
			vHolder=new ViewHolder(convertView);
			
			convertView.setTag(vHolder);
			
		}else{
			vHolder=(ViewHolder) convertView.getTag();
		}
		
		//显示数据
		showData(vHolder,datas.get(position));
		
		return convertView;
	}
	
	public abstract void showData(ViewHolder vHolder,T data);
	
	
	public class ViewHolder{
		private Map<Integer,View> views;  //用于封装从item布局中查找的控件
		private View itemView; //item布局对象
		
		public ViewHolder(View itemView){
			this.itemView=itemView;
			
			views=new HashMap<Integer,View>();
		}
		
		public View getView(int id){
			View view=views.get(id);
			if(view==null){ //第一次查找指定id的控件
				view=itemView.findViewById(id);
				
				views.put(id, view);
			}
			return view;
		}
	}

}
